package com.quarters.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.binarywang.wxpay.bean.order.WxPayMpOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.quarters.bean.ArticleOrder;
import com.quarters.bean.NoticeOrder;
import com.quarters.bean.request.*;
import com.quarters.mapper.ArticleOrderMapper;
import com.quarters.mapper.NoticeMapper;
import com.quarters.mapper.NoticeOrderMapper;
import com.quarters.service.ArticleOrderService;
import com.quarters.service.XbxWxService;
import com.quarters.util.OrderIdUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.WxMpTemplateMsgService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.api.impl.WxMpTemplateMsgServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 张子艺
 * @packge com.xbxkj.serviceimpl
 * @data 2019-06-03 11:36
 * @project Metaphysics
 */
@Service
public class WxConfigServiceImpl implements XbxWxService {

    @Autowired
    ArticleOrderMapper articleOrderMapper;
    @Autowired
    NoticeOrderMapper noticeOrderMapper;

    @Value("${weixin.appid}")
    String appid = "";
    @Value("${weixin.secret}")
    String secret = "";
    @Value("${weixin.token}")
    String token = "";
    @Value("${weixin.template.id}")
    String templateId = "";
    @Value("${weixin.template.userId}")
    String templateUserId = "";
    @Value("${weixin.template.notice}")
    String templateNotice = "";
    @Value("${weixin.template.region}")
    String templateRegion = "";
    @Value("${weixin.template.pay}")
    String templatePay = "";
    @Value("${weixin.template.regional}")
    String regional = "";


    @Value("${weixin.template.redirect.articleUrl}")
    String articleUrl = "";
    @Value("${weixin.template.redirect.pay}")
    String payUrl = "";
    @Value("${weixin.template.redirect.noticePay}")
    String noticePay = "";
    @Value("${weixin.template.redirect.noticeDetails}")
    String noticeDetails = "";

    @Value("${weixin.pay.appid}")
    String payAppid = "";
    @Value("${weixin.pay.machid}")
    String machid = "";
    @Value("${weixin.pay.key}")
    String key = "";
    @Value("${weixin.pay.box}")
    String box = "";
    @Value("${weixin.pay.tradeType}")
    String tradeType = "";
    @Value("${weixin.pay.notifyUrl}")
    String notifyUrl = "";
    @Value("${weixin.pay.noticeNotifyUrl}")
    String noticeNotifyUrl = "";
    @Value("${weixin.pay.signType}")
    String signType = "";



    @Override
    public WxPayConfig payConfig(int flag) {
        WxPayConfig config = new WxPayConfig();
        config.setMchId(machid);
        //回调地址
        if(flag==1){
            config.setNotifyUrl(notifyUrl);
        }
        if(flag==2){
            config.setNotifyUrl(noticeNotifyUrl);
        }
        config.setSignType(signType);
        config.setTradeType(tradeType);
        config.setAppId(payAppid);
        //沙箱环境的密钥是生成的
//        if (box.equals("1")) {
//            config.setUseSandboxEnv(true);
//            WxPayService wxPayService = new WxPayServiceImpl();
//            wxPayService.setConfig(config);
//            try {
//                config.setMchKey(wxPayService.getSandboxSignKey());
//            } catch (WxPayException e) {
//                e.printStackTrace();
//            }

//        } else {
            config.setMchKey(key);
            config.setUseSandboxEnv(false);
//        }

        System.out.println("config:"+config);
        return config;
    }

    @Override
    public WxPayService getConsultationWxPayService() {
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(this.payConfig(1));
        return wxPayService;
    }

    @Override
    public WxPayService getConsultationWxPayServiceNoticeOrder() {
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(this.payConfig(2));
        return wxPayService;
    }

    @Override
    public WxMpInMemoryConfigStorage config() {
        WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
        config.setAppId(appid);
        config.setSecret(secret);
        config.setToken(token);
        return config;
    }

    @Override
    public WxMpService getWxService() {
        WxMpService wxMpService = new WxMpServiceImpl();
        wxMpService.setWxMpConfigStorage(this.config());
        return wxMpService;
    }


    /**
     * @param newOrderTemplatData
     * @return 报修给标签管理员发送模板消息
     * @throws WxErrorException
     */
    @Override
    public boolean questions(NewOrderTemplatData newOrderTemplatData) throws WxErrorException {
        WxMpService service = this.getWxService();
        WxMpTemplateData templateData1 = new WxMpTemplateData();
        templateData1.setName("first");
        templateData1.setColor("#CD5C5C");
        templateData1.setValue("你好，用户提出了服务请求!");

        //报修类型   需求名称
        WxMpTemplateData templateData2 = new WxMpTemplateData();
        templateData2.setName("keyword1");
        templateData2.setValue("用户提出了服务请求");
        //报修类型   需求类别
        WxMpTemplateData templateData3 = new WxMpTemplateData();
        templateData3.setName("keyword2");
        templateData3.setValue(newOrderTemplatData.getType());
        //报修内容  希望服务区域
        WxMpTemplateData templateData4 = new WxMpTemplateData();
        templateData4.setName("keyword3");
        templateData4.setValue(newOrderTemplatData.getPhone());
        //报修手机号  有效日期
        WxMpTemplateData templateData5 = new WxMpTemplateData();
        templateData5.setName("keyword4");
        templateData5.setValue(newOrderTemplatData.getCreateTime());
        //备注
        WxMpTemplateData templateData6 = new WxMpTemplateData();
        templateData6.setName("remark");
        templateData6.setValue(newOrderTemplatData.getContent());


        List<WxMpTemplateData> list = new ArrayList<>();
        list.add(templateData1);
        list.add(templateData2);
        list.add(templateData3);
        list.add(templateData4);
        list.add(templateData5);
        list.add(templateData6);
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(templateId);
        templateMessage.setData(list);
        templateMessage.setToUser(newOrderTemplatData.getToUser());

        //templateMessage.setUrl("https://www.baidu.com/");
        WxMpTemplateMsgService templateMsgService = new WxMpTemplateMsgServiceImpl(service);
        templateMsgService.sendTemplateMsg(templateMessage);
        return true;
    }

    /**
     * @param sendArticles
     * @return 给用户推送文章
     * @throws WxErrorException
     */
    @Override
    public boolean sendArticles(SendArticles sendArticles) throws WxErrorException {
        WxMpService service = this.getWxService();

        WxMpTemplateData templateData1 = new WxMpTemplateData();
        templateData1.setName("first");
        templateData1.setColor("#CD5C5C");
        templateData1.setValue("你好，有新文章推送了!");
        //推送标题  事项名称
        WxMpTemplateData templateData2 = new WxMpTemplateData();
        templateData2.setName("keyword1");
        templateData2.setValue(sendArticles.getTiele());
        //文章状态  是想摘要
        WxMpTemplateData templateData3 = new WxMpTemplateData();
        templateData3.setName("keyword2");
        templateData3.setValue("生活推荐");
        //推送时间  处理人员
        WxMpTemplateData templateData4 = new WxMpTemplateData();
        templateData4.setName("keyword3");
        templateData4.setValue("小区业主");
        //时间
        WxMpTemplateData templateData5 = new WxMpTemplateData();
        templateData5.setName("keyword4");
        templateData5.setValue(sendArticles.getCreateTime());
        List<WxMpTemplateData> list = new ArrayList<>();
        list.add(templateData1);
        list.add(templateData2);
        list.add(templateData3);
        list.add(templateData4);
        list.add(templateData5);
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(templateUserId);
        templateMessage.setData(list);
        templateMessage.setToUser(sendArticles.getToUser());

        templateMessage.setUrl(articleUrl+"?id="+sendArticles.getArticleId());
        WxMpTemplateMsgService templateMsgService = new WxMpTemplateMsgServiceImpl(service);
        templateMsgService.sendTemplateMsg(templateMessage);
        return true;
    }


    /**
     * @param sendNotice
     * @return 给用户发送通知
     * @throws WxErrorException
     */
    @Override
    public boolean sendNotice(SendNotice sendNotice) throws WxErrorException {
        WxMpService service = this.getWxService();

        WxMpTemplateData templateData1 = new WxMpTemplateData();
        templateData1.setName("first");
        templateData1.setColor("#CD5C5C");
        templateData1.setValue("你好，有新通知了!");

        //缴费项目  业务名称
        WxMpTemplateData templateData2 = new WxMpTemplateData();
        if(sendNotice.getContent().length()>30){
            String sub = sendNotice.getContent().substring(0,30);
            templateData2.setName("keyword1");
            templateData2.setValue(sub+".....");
        }else{
            templateData2.setName("keyword1");
            templateData2.setValue(sendNotice.getContent());
        }



        //缴费金额  当前状态
        WxMpTemplateData templateData3 = new WxMpTemplateData();
        templateData3.setName("keyword2");
        templateData3.setValue("暂不通知");
        //缴费时间  处理时间
        WxMpTemplateData templateData4 = new WxMpTemplateData();
        templateData4.setName("keyword3");
        templateData4.setValue(sendNotice.getCreateTime());

        List<WxMpTemplateData> list = new ArrayList<>();
        list.add(templateData1);
        list.add(templateData2);
        list.add(templateData3);
        list.add(templateData4);
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(templateNotice);
        templateMessage.setData(list);
        templateMessage.setToUser(sendNotice.getToUser());
        System.out.println("tongzhiid:"+sendNotice.getNoticeId());
        templateMessage.setUrl(noticeDetails+"?id="+sendNotice.getNoticeId());
        WxMpTemplateMsgService templateMsgService = new WxMpTemplateMsgServiceImpl(service);
        templateMsgService.sendTemplateMsg(templateMessage);
        return true;
    }


    /**
     * @param
     * @return 给区域管理发送模板消息
     * @throws WxErrorException
     *
     *
     *  给区域管理员发送通知
     *23123121233121
     */
    @Override
    public boolean region(Region region) throws WxErrorException {
        WxMpService service = this.getWxService();

        WxMpTemplateData templateData1 = new WxMpTemplateData();
        templateData1.setName("first");
        templateData1.setColor("#CD5C5C");
        templateData1.setValue("你好，有新通知了!");
        //推送标题  认证单位
        WxMpTemplateData templateData2 = new WxMpTemplateData();
        templateData2.setName("keyword1");
        templateData2.setValue("现代小区管家增值服务");
        //审核事项
        WxMpTemplateData templateData3 = new WxMpTemplateData();
        templateData3.setName("keyword2");
        templateData3.setValue(region.getTiele());
        //审核状态
        WxMpTemplateData templateData4 = new WxMpTemplateData();
        templateData4.setName("keyword3");
        templateData4.setValue("暂无");
        //审核时间
        WxMpTemplateData templateData5 = new WxMpTemplateData();
        templateData5.setName("keyword4");
        templateData5.setValue(region.getCreateTime());

        List<WxMpTemplateData> list = new ArrayList<>();
        list.add(templateData1);
        list.add(templateData2);
        list.add(templateData3);
        list.add(templateData4);
        list.add(templateData5);
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(regional);
        templateMessage.setData(list);
        templateMessage.setToUser(region.getToUser());

        //templateMessage.setUrl(articleUrl+"?id="+sendArticles.getArticleId());
        WxMpTemplateMsgService templateMsgService = new WxMpTemplateMsgServiceImpl(service);
        templateMsgService.sendTemplateMsg(templateMessage);
        return true;
    }


    /**
     * @param pay
     * @return 给管理员发送模板消息进行支付
     * @throws WxErrorException
     */
    @Override
    public boolean pay(Pay pay) throws WxErrorException {
        WxMpService service = this.getWxService();
        ArticleOrder articleOrder = new ArticleOrder();
        NoticeOrder noticeOrder = new NoticeOrder();
        //根据订单号查询这条订单
        if(pay.getFlag()==1){
             articleOrder = articleOrderMapper.selectByOrderNumber(pay.getOrderNumber());
             System.out.println("文章订单信息:"+articleOrder);
        }else{
             noticeOrder = noticeOrderMapper.selectByOrderNumber(pay.getOrderNumber());
             System.out.println("通知订单信息:"+noticeOrder);
        }


        WxMpTemplateData templateData1 = new WxMpTemplateData();
        templateData1.setName("first");
        templateData1.setColor("#CD5C5C");
        templateData1.setValue("你好，请点击进行支付!");
        //推送标题  公司名称    pay.getOrderNumber()单号
        WxMpTemplateData templateData2 = new WxMpTemplateData();
        templateData2.setName("keyword1");
        templateData2.setValue("现代小区管家增值服务");
        //推送订单号  服务项目
        WxMpTemplateData templateData3 = new WxMpTemplateData();
        if(pay.getTitle().length()>30){
            String sub = pay.getTitle().substring(0,30);
            templateData3.setName("keyword2");
            templateData3.setValue(sub+".....");
        }else{
            templateData3.setName("keyword2");
            templateData3.setValue(pay.getTitle());
        }



        //金额
        WxMpTemplateData templateData4 = new WxMpTemplateData();
        templateData4.setName("keyword3");
        templateData4.setValue(pay.getOrderMoeny());
        //时间
//        WxMpTemplateData templateData5 = new WxMpTemplateData();
//        templateData5.setName("keyword4");
//        templateData5.setValue(pay.getCreateTime());

        List<WxMpTemplateData> list = new ArrayList<>();
        list.add(templateData1);
        list.add(templateData2);
        list.add(templateData3);
        list.add(templateData4);
        //list.add(templateData5);
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(templatePay);
        templateMessage.setData(list);
        templateMessage.setToUser(pay.getToUser());

        if(pay.getFlag()==1){
            templateMessage.setUrl(payUrl+"?id="+articleOrder.getId());
        }else{
            templateMessage.setUrl(noticePay+"?id="+noticeOrder.getId());
        }
        WxMpTemplateMsgService templateMsgService = new WxMpTemplateMsgServiceImpl(service);
        templateMsgService.sendTemplateMsg(templateMessage);
        return true;
    }


    /**
     * @param region
     * @return 审核失败给管理发送模板消息
     * @throws WxErrorException
     */
    @Override
    public boolean error(Region region) throws WxErrorException {
        WxMpService service = this.getWxService();
        WxMpTemplateData templateData1 = new WxMpTemplateData();

        if(region.getFlag()==1){
            templateData1.setName("first");
            templateData1.setColor("#CD5C5C");
            templateData1.setValue("你好，文章审核失败!");
        }else{
            templateData1.setName("first");
            templateData1.setColor("#CD5C5C");
            templateData1.setValue("你好，通知审核失败!");
        }

        //审核类型
        WxMpTemplateData templateData2 = new WxMpTemplateData();
        templateData2.setName("keyword1");
        templateData2.setValue(region.getCreateTime());
        //推送结果
        WxMpTemplateData templateData3 = new WxMpTemplateData();
        templateData3.setName("keyword2");
        templateData3.setValue(region.getTiele());
        //推送时间
//        WxMpTemplateData templateData4 = new WxMpTemplateData();
//        templateData4.setName("keyword3");
//        templateData4.setValue(region.getCreateTime());

        List<WxMpTemplateData> list = new ArrayList<>();
        list.add(templateData1);
        list.add(templateData2);
        list.add(templateData3);
        //list.add(templateData4);
        WxMpTemplateMessage templateMessage = new WxMpTemplateMessage();
        templateMessage.setTemplateId(templateRegion);
        templateMessage.setData(list);
        templateMessage.setToUser(region.getToUser());
        //templateMessage.setUrl(articleUrl+"?id="+sendArticles.getArticleId());
        WxMpTemplateMsgService templateMsgService = new WxMpTemplateMsgServiceImpl(service);
        templateMsgService.sendTemplateMsg(templateMessage);
        return true;
    }



    @Override
    public WxPayMpOrderResult mpPayOrder(int orderMoeny, String orderNum,String openId,int flag) throws WxErrorException, WxPayException {
        WxPayService service;
        if(flag == 1){
             service = this.getConsultationWxPayService();
        }else{
             service = this.getConsultationWxPayServiceNoticeOrder();
        }
        WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
        orderRequest.setBody("现代小区管家增值服务");
        orderRequest.setOutTradeNo(orderNum);
        orderRequest.setTotalFee(orderMoeny);
        orderRequest.setSpbillCreateIp("127.0.0.1");
        orderRequest.setDetail("支付订单");
        orderRequest.setOpenid(openId);
        WxPayMpOrderResult result = service.createOrder(orderRequest);
        System.err.println(result);
        return result;
    }





}
